const express     = require('express');
const app         = express();

// 引入body-parser用于解析post参数
var bodyParser = require('body-parser');

// 需要use的 application/json
app.use(bodyParser.json()); 
// application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended: true
})); 

const constants     = require('./data/constants');
const sipServer     = require('./sip/server');
const dbManager     = require('./db/dbmanager');
const settingModel  = require('./model/setting');
const cameraModel   = require('./model/camera');
const log4js        = require('./data/log');
const logger        = log4js.getLogger('request');
const mediaCtrl     = require('./controller/v1/media');

// 设置express日志
log4js.useLogger(app,logger);

// express 引入静态资源
const static = express.static('public');
app.use(static);

// 跨域
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Credentials", true)
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// express 引入28181操作路由
const gb28181Router = require('./routers/gb28181');
app.use(gb28181Router);

// express 引入媒体服务器操作路由
const mediaRouter = require('./routers/media');
app.use(mediaRouter);

// express 引入设备操作路由
const deviceRouter = require('./routers/device');
app.use(deviceRouter)
const cameraRouter = require('./routers/camera');
app.use(cameraRouter)

// express 引入管理员路由
const adminRouter = require('./routers/admin');
app.use(adminRouter);

// express 引入参数设置模块
const settingRouter = require('./routers/setting');
app.use(settingRouter);

//TODO:加载权限管理 https://github.com/OptimalBits/node_acl

/**
 * 启动 http 服务
 */ 
let server = app.listen(constants.http.port, function () {
  let host = server.address().address;
  let port = server.address().port;
  logger.info("启动 Web 服务: http://%s:%s", host, port);
  
  /**从数据库加载配置 */
  dbManager.open();
  constants.load(()=>{
      // 所有通道置为不在线状态
      cameraModel.reset();
      // 释放 rtp 资源
      mediaCtrl.resetRtpServer();
      
      settingModel.load().then((sipSetting)=>{
        if(sipSetting.sip_rtp_host){
          /**
           * 启动gb28181服务
           */
          constants.initUrl(sipSetting.sip_rtp_host);
          sipServer.start(sipSetting);
        }else{
          logger.error('没有设置sip_rtp_host变量');
        }
      });
  });
  
  
  
  process.on('SIGINT', function() {
      logger.info('停止服务，关闭数据库');
      constants.save(()=>{
        dbManager.close();
        process.exit(0);
      });
  });
  process.on('unhandledRejection', (reason, p) => {
    logger.error('Unhandled Rejection at:', p, 'reason:', reason);
  });
});